/**
 * write posts js
 */
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

 //程序的开始，最好还是放在文档加载完以后
 $(document).ready(function(){
	 editor1.run(); 
	 var saveTimer= setInterval(function(){
		 posts.autosave();	  
		     //设置提示条的内容
		  $("#p_tip p").html("<strong>提示!</strong>文章已经自动保存 保存草稿时间:"+new Date().Format("yyyy-MM-dd hh:mm:ss"));   
		},1000*1000); //每分钟保存一次
	 $("#p_publish").click(function(){posts.publish();});
     $("#p_autosave").click(function(){posts.savenopublish();});
     //why use on bind event ,this is a good case
    $("#u_tags").on("click",".u_tag",handtag.tagclick);
    $("#u_tags").on("mouseover",".u_tag",handtag.tagover);
    $("#u_tags").on("mouseout",".u_tag",handtag.tagout);
    $(".a_tag").on("click",handtag.usuallytag);
    $("#addtagbtn").click(handtag.addTag);
    loadtree.load();

 });
 
 
var editor1 = (function () {
	 //将所有的操作闭包在内部完成
	    var converter1 = Markdown.getSanitizingConverter(); 
	    converter1.hooks.chain("preBlockGamut", function (text, rbg) {
	        return text.replace(/^ {0,3}""" *\n((?:.*?\n)+?) {0,3}""" *$/gm, function (whole, inner) {
	            return "<blockquote>" + rbg(inner) + "</blockquote>\n";
	            });
	        }); 
	    var editor1 = new Markdown.Editor(converter1); 
	    editor1.hooks.set("insertImageDialog", 
	        function(y) { 
	        	$('#myModal').modal('show')
	        	var button = jQuery('#selectfile');//绑定事件
	        			var load = new AjaxUpload(button, {//绑定AjaxUpload
	        		    action: weburl+"admin/write/imgupload",//文件要上传到的处理页面,语言可以PHP,ASP,JSP等
	        		    type:"POST",//提交方式
	        		    data:{//还可以提交的值
	        		        id:$("#p_id").val()
	        		    },
	        		    autoSubmit:true,//选择文件后,是否自动提交.这里可以变成true,自己去看看效果吧.
	        		    name:'msUploadFile',//提交的名字
	        		    onChange:function(file,ext){//当选择文件后执行的方法,ext存在文件后续,可以在这里判断文件格式
	        				$("#lablefilename").text(file);  
	        		    	
	        		    },
	        		    onSubmit: function (file, ext) {//提交文件时执行的方法
	        		    	if(ext && /^(jpg|jpeg|png|gif)$/.test(ext)){
	        					//ext是后缀名
	        		    		button.value = "正在上传…";
	        		    		button.disabled = "disabled";
	        				}else{	
	        					alert("不支持的文件格式！只能上传jpg|jpeg|png|gif") ;
	        					return false;
	        				}
	        		    },
	        		    onComplete: function (file, response) {//文件提交完成后可执行的方法
	        		        button.text('浏览');
	        		        this.enable();

	        				var obj = JSON.parse(response);
	        				//console.log(obj.showsrc);
	        				$('#s_filename').val(obj.showsrc);
	        		    }
	        		});
	        	  $("#fileupload").click(function(){ 
 	        	 	  $('#myModal').modal('hide')
	        	 	   y($('#s_filename').val());
	        	 	});
	        	 $("#fileupload_href").click(function(){ 
	        	 	   y($("#imgfile_src").val());
	        	 	  $('#myModal').modal('hide')
	        	 });
	        	 $("#closeimg").click(function(){ 
	        		 setTimeout(function () { y(); }, 0);
	        	 });
	        	 $("#closeimg2").click(function(){ 
	        		  setTimeout(function () { y(); }, 0);
	        	 });
	            return true; 
	        }); 
	    //把执行的方法暴露在外面调用
	    return  editor1; 
})(); 

var posts = (function(){
  //get the values
 var title,markdowncontent,htmlcontent,tags,categoryid,id;
 function publish(){
	 var _obj = getDatas();
	 _obj.post_status = 0;
	 saveOrUpdateDb(_obj);
 }
 function autosave(){
	 var _obj = getDatas();
	 if(!_obj.hasOwnProperty('post_status'))
	   _obj.post_status = 1;
	 saveOrUpdateDb(_obj);
	// console.log("执行保存草稿");
 }
 function savenopublish(){
        var _obj = getDatas();
        //if(!_obj.hasOwnProperty('post_status'))
            _obj.post_status = 1;

        saveOrUpdateDb(_obj);
     $.layer({
         area : ['auto','auto'],
         dialog : {msg:'已保存草稿',type : 1}
     });
    }
    //set value
 function getDatas(){
	 title = $("#p_title").val();
	 markdowncontent = $("#wmd-input").val(); 
	 htmlcontent = $("#wmd-preview").html(); 
	 id = $("#p_id").val();
     //get tags
     var tageles = $(".u_tag");
     tags = new Array();
     for(var i =0;i<tageles.length;i++){
         tags[i]={"id":$(tageles[i]).attr("data"),"name":$(tageles[i]).text()}
     }
	 //console.log("get Data %s",id);
     var selectedNode = treeCompnent.tree.getCheckedNodes(true);
     var categoryid = 1;
     if(selectedNode.length > 0){
        var category  = selectedNode[0];
         categoryid = category.id;
     }
     var u_category = $("input[type='radio'][name='category_usually']:checked").val();
     if(u_category && categoryid==1){
         categoryid=u_category;
     }
     var imagesrc  = $("#imgfile_src").val();
     if(imagesrc == ""){
          imagesrc = $('#s_filename').val();
     }
    var post_status = $('#p_status').val();
	
	var p_address = $('#p_address').val();

     return {id:id,title:title,markdowncontent:markdowncontent,htmlcontent:htmlcontent,tags:tags,post_link:p_address,post_category:categoryid,"post_file_location":imagesrc,"post_status":post_status};
 }
 function saveOrUpdateDb(obj){
	 //这里会根据 
	 $.post( weburl+'admin/write/saveOrUpdate', obj, function( data ) {
		// console.log(data.id);
		 $("#p_id").val(""+data.id);
         $('#p_status').val(data.post_status);
         //发布
         var pid =data.id;
         $.post( weburl+'admin/staticmgr/postcreatebyid?id='+pid, data,
             function( data ) {
                 if(data.success){
                     if(obj.post_status == 0){
                         $.layer({
                             area : ['auto','auto'],
                             dialog : {msg:'文章发布成功',type : 1}
                         });
                    }
                 }else{
                     $.layer({
                         area : ['auto','auto'],
                         dialog : {msg:'文章发布失败',type : 1}
                     });
                 }

             },
             "json");

		}, "json");
     //console.log(obj);
 }
 return {publish:publish,autosave:autosave,savenopublish:savenopublish};
})();
/**
 * data:
 * use tag like:<span class="label label-info hand u_tag" data="1">世界坏</span>
 * usually tag like:<span class="label label-info hand a_tag" data="2">AC米兰</span>
 */
var handtag =(function (){
   function tagover(event){
       $(event.target).removeClass("label-info");
       $(event.target).addClass(" label-important");
       $(event.target).html($(event.target).text()+"&times;");

   }
   function tagout(event){
       $(event.target).removeClass("label-important");
       $(event.target).addClass("label-info");
       var tagtxt = $(event.target).html();
       $(event.target).html(tagtxt.substring(0,tagtxt.length-1));
   }
   function tagclick(event){
       //must delete next ele,then del self
       $(event.target).next().remove();
       $(event.target).remove();
   }
    //get all tags
   function allTags(){
      var tags = $(".u_tag");
      return tags;
   }
    //judege add tag or not ,is this tag exist can add
   function canAddTag(tagid){
     var tags = allTags();
     for(var i = 0;i<tags.length;i++){
        // console.log($(tags[i]).attr("data") );
         if($(tags[i]).attr("data") == tagid ){
             return false;
         }
     }
       return true;
   }
   function addUsuallyTag(event){
       var selecttag = $(event.target);
       if(canAddTag(selecttag.attr("data"))){
         var appendtag =  $('<span class="label label-info hand u_tag" data="'+selecttag.attr("data")+ '">'+selecttag.text()+'</span><br/>');
        $("#u_tags").append(appendtag);
      }
   }
   function addTag(){
       var tagname = $("#addtaginput").val();
       //这里会根据
       $.post( weburl+'admin/tags/addTag', {"tagname":tagname}, function( data ) {
            addTagtoUse(data.id,data.name);
       }, "json");
   }
    function addTagtoUse(tagid,tagname){
        if(canAddTag(tagid)){
            var appendtag =  $('<span class="label label-info hand u_tag" data="'+tagid+ '">'+tagname+'</span><br/>');
            $("#u_tags").append(appendtag);
        }
    }
    return {
        tagover:tagover,
        tagout:tagout,
        tagclick:tagclick,
        usuallytag:addUsuallyTag,
        addTag:addTag
    }

})();

var loadtree =(function(){
    //$("#categorytree")
    function loadtree(){
    	//为基本的树结构增加可以勾选的属性
    	treeCompnent.setting.check = {enable: true,chkStyle: "radio",radioType: "all",autoCheckTrigger: true};

    	treeCompnent.initTree(parms);
    };
    return {load:loadtree}
})();



